1 import random
2 from words import word_list
3
4
5 def get_word():
6 word = random.choice(word_list)
7 return word.upper()
8
9
10 def play(word):
11 word_completion = "_" * len(word)
12 guessed = False
13 guessed_letters = []
14 guessed_words = []
15 tries = 6
16 print("=====Hang Man Game=====")
17 print(display_hangman(tries))
18 print(word_completion)
19 print("\n")
20 while not guessed and tries > 0:
21 guess = input("Please guess a letter or word: ").upper()
22 if len(guess) == 1 and guess.isalpha():
23 if guess in guessed_letters:
24 print("You already guessed the letter", guess)
25 elif guess not in word:
26 print(guess, "is not in the word.")
27 tries -= 1
28 guessed_letters.append(guess)
29 else:
30 print("Good job,", guess, "is in the word!")
31 guessed_letters.append(guess)
32 word_as_list = list(word_completion)
33 indices = [i for i, letter in enumerate(word) if letter == guess]
34 for index in indices:
35 word_as_list[index] = guess
36 word_completion = "".join(word_as_list)
37 if "_" not in word_completion:
38 guessed = True
39 elif len(guess) == len(word) and guess.isalpha():
40 if guess in guessed_words:
41 print("You already guessed the word", guess)
42 elif guess != word:
43 print(guess, "is not the word.")
44 tries -= 1
45 guessed_words.append(guess)
46 else:
47 guessed = True
48 word_completion = word
49 else:
50 print("Not a valid guess.")
51 print(display_hangman(tries))
52 print(word_completion)
53 print("\n")
54 if guessed:
55 print("Congrats, you guessed the word! You win!")
56 else:
57 print("Sorry, you ran out of tries. The word was " + word + ". Maybe next time!")
58
59
60 def display_hangman(tries):
61 stages = [ # final state: head, torso, both arms, and both legs
62 """
63 --------
64 | |
65 | O
66 | \\|/
67 | |
68 | / \\
69 -
70 """,
71 # head, torso, both arms, and one leg
72 """
73 --------
74 | |
75 | O
76 | \\|/
77 | |
78 | /
79 -
80 """,
81 # head, torso, and both arms
82 """
83 --------
84 | |
85 | O
86 | \\|/
87 | |
88 |
89 -
90 """,
91 # head, torso, and one arm
92 """
93 --------
94 | |
95 | O
96 | \\|
97 | |
98 |
99 -
100 """,
101 # head and torso
102 """
103 --------
104 | |
105 | O
106 | |
107 | |
108 |
109 -
110 """,
111 # head
112 """
113 --------
114 | |
115 | O
116 |
117 |
118 |
119 -
120 """,
121 # initial empty state
122 """
123 --------
124 | |
125 |
126 |
127 |
128 |
129 -
130 """
131 ]
132 return stages[tries]
133
134
135 def main():
136 word = get_word()
137 play(word)
138 while input("Play Again? (Y/N) ").upper() == "Y":
139 word = get_word()
140 play(word)
141
142
143 if __name__ == "__main__":
144 main()